package com.kzj.kzj_rabbitmq.consumer;

import com.alibaba.fastjson.JSON;

import com.kzj.kzj_rabbitmq.common.*;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Date;

/**
 * @Auther: cjw
 * @Date: 2018/6/28 16:06
 * @Description:消息消费者
 */

@Component
@RabbitListener(queues = QueueContent.MESSAGE_QUEUE_NAME)
public class MessageConsumer {

    static Logger logger = LoggerFactory.getLogger(MessageConsumer.class);

    @RabbitHandler
    public void handler(String msg,Channel channel, Message message) throws IOException {
        if (!StringUtils.isEmpty(msg)) {
            MessagePojo messagePojo = JSONUtil.toBean(msg,MessagePojo.class);
            try {
                //这里使用策略模式和Spring的结合使用，通过applicationContext获取类
                Strategy s =  (Strategy)SpringContextUtil.getBean(messagePojo.getClassName());
                s.doJob(messagePojo.getParams());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//                logger.info("[MessageConsumer延时消息消费时间]"+DateUtil.datetoString(new Date()) + JSON.toJSONString(messagePojo) + ",消息ID：" + messagePojo.getMessageId());
                System.out.println("消息消费时间：" + DateUtil.datetoString(new Date()) + ",消费的消息：" + JSON.toJSONString(messagePojo));
            } catch (Exception e) {
                logger.error("确认消费异常",e);
                //记录下这条消息
                //丢弃这条消息（会通知服务器把此队列删掉）
                //channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);
                //消息重新回到队列(监听会不断消费此消息)
//                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);

            }

        }
    }

}